import React, { useState, useEffect } from 'react';
import { View, Text, Textarea } from '@tarojs/components';
import { Tabs, Button, Image } from '@nutui/nutui-react-taro';
import { Notice, File, Check, Warning, Photograph } from '@nutui/icons-react-taro';
import Taro from '@tarojs/taro';
import { dailyTaskApi } from '../../services/dailyTaskApi';

import './index.scss';
import { BASE_URL } from '../../services/request';

// 将所有数据提取为常量，避免在组件中生成
const TASK_TABS = [
  { title: '今日任务', value: '0' },
  { title: '日报表单', value: '1' },
];

// 简化的组件
const TaskPage = () => {
  // 所有 hooks 放在组件顶部
  const [activeTab, setActiveTab] = useState('0');
  const [tasks, setTasks] = useState([]);
  const [loading, setLoading] = useState(false);
  const [reportStatus, setReportStatus] = useState(false);

  // 日报表单相关状态
  const [reportContent, setReportContent] = useState('');
  const [fileList, setFileList] = useState([]);
  const [currentDate, setCurrentDate] = useState('');

  // 日报相关状态
  const [dailyReport, setDailyReport] = useState(null);

  // 模拟从后端获取任务
  const fetchTasks = async () => {
    try {
      setLoading(true);
      const res = await dailyTaskApi.getTaskList();
      setTasks(res.tasks[0]?.parsed_tasks || []);
      setReportStatus(res.tasks[0]?.completed || false);

      if (res.tasks[0]?.completed) {
        const reportRes = await dailyTaskApi.getDailyReport();
        setDailyReport(reportRes);
        console.log(reportRes);
      }
    } catch (error) {
      console.error('获取任务失败:', error);
      setTasks([]);
      setReportStatus(false);
    } finally {
      setLoading(false);
    }
  };


  // 格式化当前日期
  const formatCurrentDate = () => {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();

    // 获取星期几
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
    const weekDay = weekDays[date.getDay()];

    return `${year}年${month}月${day}日 星期${weekDay}`;
  };

  // 加载任务数据和日报状态
  useEffect(() => {
    // 设置当前日期
    setCurrentDate(formatCurrentDate());

    // 加载任务列表
    fetchTasks()
      .then()
  }, []);

  // 事件处理函数
  const handleTabChange = (value) => {
    setActiveTab(value);
  };

  // 自定义选择图片上传
  const handleChooseImage = () => {
    // 检查是否已达到最大图片数量限制
    if (fileList.length >= 4) {
      showToastMessage('最多只能上传4张图片');
      return;
    }

    // 计算还能选择的图片数量
    const remainingCount = 4 - fileList.length;

    Taro.chooseImage({
      count: remainingCount, // 限制每次选择的图片数量为剩余可上传数量
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        const newFileList = tempFilePaths.map((path, index) => ({
          url: path,
          status: 'success',
          message: '上传成功',
          name: `image-${Date.now()}-${index}.jpg`,
          type: 'image',
          uid: Date.now() + index
        }));

        setFileList([...fileList, ...newFileList]);
      },
      fail: function (err) {
        console.error('选择图片失败', err);
        showToastMessage('选择图片失败');
      }
    });
  };

  // 删除图片
  const handleDeleteImage = (file, index) => {
    const newFileList = [...fileList];
    newFileList.splice(index, 1);
    setFileList(newFileList);
  };

  // 显示提示信息
  const showToastMessage = (message) => {
    Taro.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
  };

  // 提交日报表单
  const handleSubmitReport = async () => {
    try {
      // 加上为空判断
      if (!reportContent) {
        showToastMessage('请填写今日完成情况');
        return;
      }
      // 加上确认提交的提示
      Taro.showModal({
        title: '确认提交',
        content: '确定要提交今日学习日报吗？',
        success: async res => {
          if (res.confirm) {
            Taro.showLoading({ title: '正在提交...' });
            // 准备请求数据
            const requestData = {
              report_text: reportContent,
              pictures: []  // 这将是带前缀的base64字符串的数组
            };

            // 如果有图片，将其转换为Base64
            if (fileList.length > 0) {
              const fileManager = Taro.getFileSystemManager();

              // 将所有图片转换为Base64并收集到数组中
              const base64Promises = fileList.map(file => {
                return new Promise((resolve, reject) => {
                  fileManager.readFile({
                    filePath: file.url,
                    encoding: 'base64',
                    success: res => {
                      // 获取文件扩展名来确定MIME类型
                      const extension = file.url.split('.').pop().toLowerCase();
                      let mimeType = 'image/jpeg'; // 默认MIME类型

                      // 根据扩展名确定MIME类型
                      if (extension === 'png') mimeType = 'image/png';
                      else if (extension === 'gif') mimeType = 'image/gif';
                      else if (extension === 'webp') mimeType = 'image/webp';
                      else if (extension === 'svg') mimeType = 'image/svg+xml';

                      // 构建完整的Data URL
                      const dataUrl = `data:${mimeType};base64,${res.data}`;
                      resolve(dataUrl);
                    },
                    fail: err => reject(err)
                  });
                });
              });

              // 等待所有图片转换完成
              requestData.pictures = await Promise.all(base64Promises);
            }
            try {
              // 提交请求
              await dailyTaskApi.setDailyReport(requestData);
              await fetchTasks();
            } catch (error) {
              console.error('提交日报失败:', error);
              showToastMessage('提交日报失败');
            }

            // 提交成功后清空表单并显示成功提示
            Taro.hideLoading();
            setReportContent('');
            setFileList([]);
            showToastMessage('日报提交成功！');
            setReportStatus(true);
          }
          if (res.cancel) {
            showToastMessage('已取消提交');
            return;
          }
        }
      });



    } catch (error) {
      console.error('提交日报失败:', error);
      showToastMessage('提交日报失败');
    }
  };

  // 渲染函数 - 分解为较小的部分
  const renderTaskStatsCards = () => (
    <View className="task-stats-row">
      {/* 任务总数卡片 */}
      <View className="stat-card task-count-card">
        <Text className="stat-title">今日任务总数</Text>
        <View className="stat-content">
          <View className="count-icon-container">
            <View className="count-icon">
              <File />
            </View>
          </View>
          <Text className="stat-value">{tasks?.length || 0}</Text>
        </View>
      </View>

      {/* 日报填写状态卡片 */}
      <View className="stat-card report-status-card">
        <Text className="stat-title">日报是否填写</Text>
        <View className="stat-content">
          {loading ? (
            <Text className="status-text loading">检查中...</Text>
          ) : reportStatus ? (
            <View className="status-container submitted">
              <View className="status-icon">
                <Check />
              </View>
              <Text className="status-text">是</Text>
            </View>
          ) : (
            <View className="status-container not-submitted">
              <View className="status-icon">
                <Warning />
              </View>
              <Text className="status-text">否</Text>
            </View>
          )}
        </View>
      </View>
    </View>
  );

  const renderTaskItem = (task, index) => {
    return (
      <View key={task.id || index} className="task-item">
        <View className="task-index">{index + 1}</View>
        <View className="task-content">
          <View className="task-title" onTap={() => showTaskDetail(task)}>{task.sub_tasks || '未命名任务'}</View>
        </View>
      </View>
    );
  }

  const showTaskDetail = (task) => {
    // 一直显示气泡
    Taro.showModal({
      content: task.sub_tasks,
      success: () => {
        Taro.hideToast();
      },
      showCancel: false
    });
  }

  const renderTaskList = () => (
    <View className="task-list-section">
      <View className="section-header">
        <Text className="section-title">今日任务清单</Text>
        {!reportStatus && (
          <View className="report-reminder">
            <Notice />
            <Text className="reminder-text">别忘了提交日报</Text>
          </View>
        )}
      </View>

      <View className="task-list">
        {loading ? (
          <View className="loading-state">加载任务中...</View>
        ) : (tasks || []).length > 0 ? (
          tasks.map((task, index) => renderTaskItem(task, index))
        ) : (
          <View className="empty-state">暂无任务</View>
        )}
      </View>
    </View>
  );

  const renderTodayTab = () => (
    <View className="task-today">
      {renderTaskStatsCards()}
      {renderTaskList()}
    </View>
  );

  const renderImageUploader = () => (
    <View className="image-uploader-container">
      <View className="uploaded-images-list">
        {fileList.map((file, index) => (
          <View key={file.uid} className="image-preview-item">
            <Image
              src={file.url}
              className="preview-image"
              mode="aspectFill"
            />
            <View
              className="delete-image-btn"
              onClick={() => handleDeleteImage(file, index)}
            >
              ×
            </View>
          </View>
        ))}

        {fileList.length < 4 && (
          <View
            className="add-image-button"
            style={fileList.length === 0 ? { width: '100%' } : {}}
            onClick={handleChooseImage}
          >
            <Photograph size="20" />
            <Text className="add-text">添加图片</Text>
          </View>
        )}
      </View>

      <View className="image-limit-hint">
        <Text className="hint-text">最多上传4张图片 {fileList.length}/4</Text>
      </View>
    </View>
  );

  const renderReportTab = () => {
    if (!reportStatus) {
      return (
        <View className="daily-report">
          <View className="report-header">
            <Text className="report-title">今日学习日报</Text>
          </View>

          <View className="report-form">
            <View className="form-item">
              <Text className="form-label">日期</Text>
              <View className="date-field">
                <Text>{currentDate}</Text>
              </View>
            </View>

            <View className="form-item">
              <Text className="form-label">今日完成情况</Text>
              <Textarea
                className="form-textarea"
                placeholder="描述今天的学习内容和完成情况..."
                maxLength={1000}
                value={reportContent}
                onInput={(e) => setReportContent(e.detail.value)}
              />
            </View>

            <View className="form-item">
              <Text className="form-label">上传图片</Text>
              {renderImageUploader()}
            </View>

            <Button
              className="submit-button"
              type="primary"
              onClick={handleSubmitReport}
            >
              提交日报
            </Button>
          </View>
        </View>
      );
    } else {
      return (
        <View className="daily-report submitted-report">
          <View className="report-header">
            <Text className="report-title">今日学习日报</Text>
            <View className="report-date">{currentDate}</View>
          </View>

          <View className="report-content-section">
            <View className="section-title">
              <View className="title-icon"></View>
              <Text>学习内容记录</Text>
            </View>
            <View className="report-content-text">
              {dailyReport?.report_info?.report_text || "暂无内容"}
            </View>

            {dailyReport?.report_info?.report_picture && dailyReport.report_info.report_picture.length > 0 && (
              <View className="report-images">
                {dailyReport.report_info.report_picture.map((pic, index) => (
                  <Image
                    key={index}
                    src={BASE_URL + pic}
                    className="report-image"
                    mode="aspectFill"
                    onClick={() => {
                      Taro.previewImage({
                        current: BASE_URL + pic,
                        urls: dailyReport.report_info.report_picture.map(pic => BASE_URL + pic)
                      })
                    }}
                  />
                ))}
              </View>
            )}
          </View>

          <View className="report-review-section">
            <View className="section-title">
              <View className="title-icon"></View>
              <Text>学习评估结果</Text>
            </View>

            <View className="score-cards">
              <View className="score-card">
                <View className="score-name">任务完成</View>
                <View className="score-value">{dailyReport?.report_info?.report_review?.basic?.score || 0}</View>
                <View className="score-desc">{dailyReport?.report_info?.report_review?.basic?.review || ""}</View>
                <View className={`score-bg basic-${Math.floor((dailyReport?.report_info?.report_review?.basic?.score || 0) / 20)}`}></View>
              </View>

              <View className="score-card">
                <View className="score-name">额外任务</View>
                <View className="score-value">{dailyReport?.report_info?.report_review?.excess?.score || 0}</View>
                <View className="score-desc">{dailyReport?.report_info?.report_review?.excess?.review || ""}</View>
                <View className={`score-bg excess-${Math.floor((dailyReport?.report_info?.report_review?.excess?.score || 0) / 20)}`}></View>
              </View>

              <View className="score-card">
                <View className="score-name">其他内容</View>
                <View className="score-value">{dailyReport?.report_info?.report_review?.extra?.score || 0}</View>
                <View className="score-desc">{dailyReport?.report_info?.report_review?.extra?.review || ""}</View>
                <View className={`score-bg extra-${Math.floor((dailyReport?.report_info?.report_review?.extra?.score || 0) / 20)}`}></View>
              </View>

            </View>
          </View>

          <View className="total-score-section">
            <View className="total-score-container">
              <View className="total-score-ring">
                <View className="total-score-value">{dailyReport?.report_info?.report_review?.total?.score || 0}</View>
                <View className="total-score-label">总分</View>
              </View>
            </View>
            <View className="total-score-review">
              {dailyReport?.report_info?.report_review?.total?.review || "暂无评价"}
            </View>
          </View>
        </View>
      );
    }
  }

  // 主渲染
  return (
    <View className="task-page">
      {tasks.length > 0 ? (
        <>
          <Tabs
            value={activeTab}
            onChange={handleTabChange}
            activeType="button"
          >
            {TASK_TABS.map((tab) => (
              <Tabs.TabPane key={tab.value} title={tab.title} value={tab.value} />
            ))}
          </Tabs>

          {activeTab === '0' ? renderTodayTab() : renderReportTab()}
        </>
      ) : (
        <View className="no-task">
          <View className="no-task-content">
            <View className="no-task-icon">
              <File size="48" />
            </View>
            <Text className="no-task-title">今日暂无任务</Text>
            <Text className="no-task-desc">检查周期任务是否结束，可以提醒组长布置!</Text>
            <View className="no-task-decoration-1"></View>
            <View className="no-task-decoration-2"></View>
            <View className="no-task-decoration-3"></View>
          </View>
        </View>
      )}
    </View>
  );
};

export default TaskPage;